const router = require('koa-router')()
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { login } = require('../controller/user')

router.prefix('/api/user')

router.post('/login',async (ctx, next) => {
  const { username, password } = ctx.request.body
  const result = login(username, password)

  return result.then(data => {
    if (data.username) {
      ctx.session.username = data.username
      ctx.session.realname = data.realname
      
      ctx.body = new SuccessModel('登录成功')
      return
    }
    ctx.body = new ErrorModel('未登录')
  })
})

router.get('/login-test', async (ctx, next) => {
  if (ctx.session.username) {
    ctx.body = new SuccessModel('已登录')
    return
  }
  ctx.body = new ErrorModel('未登录')
})

// session 测试
// router.get('/session', async (ctx, next) => {
//   // ctx.session = 'test-session'
//   console.log(ctx.session)
//   let num = ctx.session.views || 0
//   ctx.session.views = ++ num
//   ctx.body = {
//     code: 0,
//     session: '测试'
//   }
// })


module.exports = router
